from paho.mqtt import client as mqtt_client
from uuid import uuid4
import logging
import ssl

class MqttAdmin(object):
    gmy_self = None

    def __init__(self):
        logging.debug(f'enter MqttAdmin')
        super().__init__()
        MqttAdmin.gmy_self = self
        self._client_id = uuid4().hex
        self._client = None

    def mqtt_client_id(self):
        return self._client_id

    def mqtt_connect(self, broker, port, ca_crt = None, client_crt = None, client_key = None, insecure = True):
        if self._client:
            return self._client
        def on_connect(client, userdata, flags, rc):
            MqttAdmin.gmy_self.mqtt_on_connect(client, userdata, flags, rc)

        self._client = mqtt_client.Client(self._client_id)
        self._client.tls_set(ca_certs = ca_crt, certfile = client_crt, keyfile = client_key, tls_version=ssl.PROTOCOL_TLSv1_2)
        self._client.tls_insecure_set(insecure)
        self._client.on_connect = on_connect
        self._client.connect(broker, port)
        self._client.loop_start()
        return self._client

    def mqtt_subscribe(self, topic):
        def on_message(client, userdata, msg):
            MqttAdmin.gmy_self.mqtt_on_message(client, userdata, msg)
        self._client.on_message = on_message
        self._client.subscribe(topic)

    def mqtt_publish(self, topic, msg):
        self._client.publish(topic, msg) 

    def mqtt_on_connect(self, client, userdata, flags, rc):
        #走到这里是错误的，这个函数应该被继承实现
        logging.debug('goto here mqtt_on_connect is error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        if rc == 0:
            logging.debug("Connected to MQTT Broker!")
        else:
            logging.debug("Failed to connect, return code %d\n", rc) 

    def mqtt_on_message(self, client, userdata, msg):
        #走到这里是错误的，这个函数应该被继承实现
        logging.debug('goto here mqtt_on_message is error!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        logging.debug(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")


# #test
# ma = MqttAdmin()


# topic_rx = '/vpn/rx'
# topic_tx = '/vpn/tx'
# ma.mqtt_connect('liuchenxi.love', 1883)
# ma.mqtt_subscribe(topic_rx)
# ma.mqtt_publish(topic_tx, 'I am coming')

# import time

# count =0
# while True:
#     ma.mqtt_publish(topic_tx, 'I am coming %s times'%count)
#     count = count + 1
#     time.sleep(1)
#     logging.debug('waitxxx %s'%count)